package com.bop.dehong.util;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;

import com.bop.dehong.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ImageLoaderUtils {
	private static ImageLoader imageLoader;
	private volatile static ImageLoaderUtils instance;

	private ImageLoaderUtils(Context context) {
		imageLoader = ImageLoader.getInstance();
	}

	public static ImageLoaderUtils getInstance(Context context) {
		if (instance == null) {
			synchronized (ImageLoaderUtils.class) {
				if (instance == null) {
					instance = new ImageLoaderUtils(context);
				}
			}
		}
		return instance;
	}
	public ImageLoader getImageLoader(){
		return imageLoader;
	}

	public void setImageNetResource(ImageView iv, String url) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.img_default)
				.showImageForEmptyUri(R.drawable.img_default)
				.showImageOnFail(R.drawable.img_default).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				// .displayer(new RoundedBitmapDisplayer(20))
				.build();
		ImageLoadingListener listener = new AnimateFirstDisplayListener();
		imageLoader.displayImage(url, iv, options, listener);
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	public void clearCache() {
		imageLoader.clearDiskCache();// 本地缓存
		imageLoader.clearMemoryCache();// 内存缓存
	}
}
